package com.ysw.wisdomcampus.model

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.widget.TextView
import android.widget.Toast
import androidx.preference.PreferenceManager
import com.google.gson.Gson
import com.ysw.wisdomcampus.R
import com.ysw.wisdomcampus.model.tab.Student
import com.ysw.wisdomcampus.model.tab.SubjectPus
import com.zhuangfei.timetable.core.SubjectBean
import org.koin.java.KoinJavaComponent
import org.litepal.LitePal
import org.litepal.extension.updateAll
import java.io.InputStream


inline val projectModel: ProjectModel
    get() = KoinJavaComponent.getKoin().get()

class ProjectModel(
    val context: Context
) {

    companion object {
        const val TAG = "DbModel"
        const val STATUDENT_ID = "studentId"
        const val PASSWORD = "password"
    }

    val students = mutableListOf<Student>()

    fun initDb() {
        if (LitePal.findFirst(Student::class.java) == null) {
            Gson().fromJsonString<Students>(context.assets.open("student.json"))
                .students.apply { for (s in this) s.save() }
            students.apply {
                clear()
                addAll(LitePal.findAll(Student::class.java))
            }
        }

        if (LitePal.findFirst(SubjectPus::class.java) == null) {
            Gson().fromJsonString<Subjects>(context.assets.open("subject.json"))
                .subjects.apply {
                    for (s in this) {
                        SubjectPus(
                            name = s.name,
                            room = s.room,
                            teacher = s.teacher,
                            start = s.start,
                            step = s.step,
                            day = s.day,
                            colorRandom = s.colorRandom,
                            time = "",
                            done = -1
                        ).save()
                    }
                }
        }
    }

    /**
     * 课程数据库
     */
    val subjectPlus = mutableListOf<SubjectPus>()
    fun setDone(
        day: Int,
        start: Int
    ) {
        Log.d(TAG, "setDone: ${day}, ${start} ")
        val contentValues = ContentValues().apply { put("done", 1) }
        LitePal.updateAll(SubjectPus::class.java, contentValues,"day = ? and start = ?",
            "$day", "$start")

    }

    fun queryDone() = LitePal.where("done = ?", "1").find(SubjectPus::class.java)


    class Subjects {
        val subjects = mutableListOf<SubjectBean>()
    }

    class Students {
        val students = mutableListOf<Student>()
    }

    /**
     * 学科数据 [SubjectBean]
     */
    val subjects = Gson().fromJsonString<Subjects>(context.assets.open("subject.json")).subjects

    var activeStudent: Student? = null


    /**
     * 按照条件查询学生
     *
     * @param condition String  查询条件
     * @param conditionValue1 String 查询条件的具体值
     * @return Student
     */
    fun query(
        condition1: String = "",
        condition2: String = "",
        conditionValue1: String = "",
        conditionValue2: String = ""
    ): Student? = when {
        condition1 != "" && condition2 == "" ->
            LitePal.where("$condition1 = ?", conditionValue1)
                .findFirst(Student::class.java)
        condition1 != "" && condition2 != "" ->
            LitePal.where("$condition1 = ? and $condition2 = ?", conditionValue1, conditionValue2)
                .findFirst(Student::class.java)
        else -> null
    }

    fun update(
        studentId: String,
        condition: String,
        modification: String
    ) {
        val contentValue =  ContentValues()
        contentValue.put(condition, modification)
        LitePal.updateAll(Student::class.java, contentValue, "studentId = ?", studentId)
        activeStudent = query(condition1 = "studentId", conditionValue1 = activeStudent!!.studentId)
    }


    @SuppressLint("InflateParams")
    fun toast(msg: Any) {
        Toast(context).apply {
            view = LayoutInflater.from(context).inflate(R.layout.toast, null)
            view!!.findViewById<TextView>(R.id.text).text = msg.toString()
            duration = Toast.LENGTH_SHORT
            show()
        }
    }

    fun putSp(studentId: String) {
        PreferenceManager.getDefaultSharedPreferences(context).edit().apply {
            putString("ID", studentId)
            apply()
        }
    }
}

inline fun <reified T : Any> Gson.fromJsonString(inputStream: InputStream): T {
    val out = StringBuffer()
    val b = ByteArray(4096)
    var n: Int
    while (inputStream.read(b).also { n = it } != -1) {
        out.append(String(b, 0, n))
    }
    inputStream.close()
    return Gson().fromJson(out.toString(), T::class.java)
}